<?php

namespace Beerus\Modules\BrandRights\Controllers;

use Doctrine\DBAL\Exception;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Grid;
use Biz\tools\helper\Common;
use Illuminate\Http\Request;
use App\Pockets\GridDataModel;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Encore\Admin\Grid\Displayers\Actions;
use Biz\model\brandRights\BrandRightsSource;
use Illuminate\Contracts\Foundation\Application;
use Biz\service\BrandRights\BrandRightsSourceService;

/**
 * Description: 基础权益管理
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/12/21
 * Time: 18:17
 */
class IndexController extends Controller
{
    const CHILD_STATUS_ON = 1;
    const CHILD_STATUS_OFF = 0;
    const CHILD_STATUS_ARR = [
        self::CHILD_STATUS_OFF => "关闭",
        self::CHILD_STATUS_ON => "开启"
    ];

    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        Admin::script($this->auditScript());
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $params['per_page'] = $page_size;
        $where = $this->_getWhere($params);
        $list = BrandRightsSourceService::getList($where);
        unset($where['LIMIT']);
        $count = BrandRightsSource::selectCount($where);
        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 3, function ($filter) {
                        $allSourceRights = BrandRightsSourceService::getAll(['id','rights_title']);
                        $allSourceRightsKv = array_column($allSourceRights,'rights_title','id');
                        $filter->equal('id', '权益id')->select($allSourceRightsKv);
                        $filter->equal('rights_name', '权益英文标识')->placeholder('权益英文标识');

                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('rights_group', '运营分类')->select(BrandRightsSource::RIGHTS_GROUPS);
                        $filter->equal('rights_business_scene', '适用业务')->select(BrandRightsSource::FIT_BUSINESS_SCENES);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('rights_type', '权益类型')->select(BrandRightsSource::RIGHTS_TYPE_ARR);
                        $filter->equal('data_status', '状态')->select(BrandRightsSource::STATUS_ARR);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', '权益id')->sortable();
                $grid->column('rights_title', '权益名称');
                $grid->column('rights_name', '权益英文名称')->copyable();
                $grid->column('rights_type', '权益类型')->using(
                    BrandRightsSource::RIGHTS_TYPE_ARR
                    , '未知')->label([
                    BrandRightsSource::RIGHTS_TYPE_OPEN => 'warning',
                    BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM => 'info',
                    BrandRightsSource::RIGHTS_TYPE_NUM => 'success',
                    BrandRightsSource::RIGHTS_TYPE_OTHER => 'default',
                ]);

                $grid->column('price', '单价');
                $grid->column('rights_business_scene', '适用业务')->display(function($rightsBusinessScene){
                    $rightsBusinessSceneMap = [
                        1=>'品牌',
                    ];
                    return $rightsBusinessSceneMap[$rightsBusinessScene] ?? '';
                });

                $grid->column('rights_desc', '权益说明');

                $grid->column('rights_use_pic', '查看使用说明')->display(function ($rights_use_pic){
                    if(!empty($rights_use_pic)) {
                        $img = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $rights_use_pic, ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                        return "<a href='$img' target='_blank' alt='{$this->rights_name}'>查看</a>";
                    }
                    return ' - ';
                });

                $grid->column('sort_weight', '排序')->editable();

                $grid->column('data_status', '状态')->using(
                    BrandRightsSource::STATUS_ARR
                    , '未知')->label([
                    BrandRightsSource::STATUS_NORMAL => 'success',
                    BrandRightsSource::STATUS_DELETE => 'danger',
                ]);

                $grid->setActionClass(Actions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
//                    $status = $actions->row->data_status;
//                    if ($status != BrandRightsSource::STATUS_DELETE) {
//                        $html_delete = ' <a class="fa fa-trash" data-state="' . BrandRightsSource::STATUS_DELETE . '" data-id="' . $actions->row->id . '" href="javascript:void(0);" style="margin-right: 5px">
//                                    <span class="glyphicon" aria-hidden="true">删除</span></a>';
//                        $actions->append($html_delete);
//                    }
                });
            }
        );
//        $tab = new Tab();
//        $tab->add('基础权益管理列表', $grid->render(), true);
        $content->row($grid);

        return $content
            ->header('基础权益管理列表')
            ->description(' ')
            ->breadcrumb(['text' => '基础权益管理列表', 'url' => '/BrandRights/index']);
    }


    /**
     * 获取查询条件
     * @param $params
     * @return array
     */
    private function _getWhere($params): array
    {
        $type = $params['rights_type'];
        $rights_id = $params['id'] ?? '';
        $rights_name = $params['rights_name'] ?? '';
        $rights_group = $params['rights_group'] ?? null;
        $rights_business_scene = $params['rights_business_scene'] ?? null;
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 20;
        $status = isset($params['data_status']) && $params['data_status'] != '' ? $params['data_status'] : null;
        if ($type) {
            $where['rights_type'] = $type;
        }
        if ($rights_id) {
            $where['id'] = $rights_id;
        }
        if ($rights_name) {
            $where['rights_name[~]'] = $rights_name . '%';
        }
        if($rights_group){
            $where['rights_group'] = $rights_group;
        }
        if($rights_business_scene){
            $where['rights_business_scene'] = $rights_business_scene;
        }
        $where['LIMIT'] = [
            ($page - 1) * $per_page,
            $per_page,
        ];
        if (!is_null($status)) {
            $where['data_status'] = $status;
        }
        if (isset($params['_sort']["column"], $params['_sort']["type"])) {
            $where['ORDER'] = [
                $params['_sort']["column"] => strtoupper($params['_sort']["type"]),
            ];
        }else{
            $where['ORDER'] = [
                'sort_weight' => 'ASC'
            ];
        }
        return $where;
    }

    /**
     * 更改权益状态
     * @param Request $request
     * @return JsonResponse
     */
    public function audit(Request $request): JsonResponse
    {
        try {
            $params = $request->all();

            $rule = [
                'id' => 'required|int',
                'data_status' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new \Exception($validator_msg);
            }
            $admin_id = Admin::user()->id;
            $data['id'] = $params['id'];
            $data['admin_id'] = $admin_id;
            $data['data_status'] = $params['data_status'];
            $info = BrandRightsSource::getInfo(['id' => $params['id']]);
            if (empty($info)) {
                throw new \Exception('不存在的权益');
            }
            BrandRightsSourceService::audit($data);
            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);

    }

    /**
     * 更改权益排序
     * @param Request $request
     * @return JsonResponse
     */
    public function sortWeight(Request $request,$id): JsonResponse
    {
        try {
            $params = $request->all();

            $rule = [
                'name'=>'required|string',
                'value' => 'required|int',
                'pk' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new \Exception($validator_msg);
            }
            if($params['name'] != 'sort_weight'){
                throw  new \Exception('异常操作');
            }
            $admin_id = Admin::user()->id;
            $data['admin_id'] = $admin_id;
            $data['sort_weight'] = $params['value'];
            $info = BrandRightsSource::getInfo(['id' => $params['pk']]);
            if (empty($info)) {
                throw new \Exception('不存在的权益');
            }
            $this->updateData($params['pk'],$data);
            $success = [
                'message' => '操作成功',
                'status' => true,
            ];
        } catch (\Exception $e) {
            $success = [
                'message' => '操作失败,' . $e->getMessage(),
                'status' => false,
            ];
        }

        return response()->json($success);

    }


    /**
     * 更改权益状态js
     * @return string
     */
    private function auditScript()
    {
        return <<<SCRIPT
        $('.edit-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var status=$(this).data('state');
            let url = '/admin/BrandRights/audit'
            let params = {id:id,data_status:status}
            swal({
                    title: "确认提交吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }

    /**
     * 编辑
     * @param $id
     * @param Content $content
     * @return Content|RedirectResponse
     */
    public function edit($id, Content $content)
    {
        if (!$id) {
            admin_error('参数错误！', 'warning');
        }
        $where['id'] = $id;
        //编辑wiki
        $baseInfo = BrandRightsSource::getInfo($where);
        if (!$baseInfo) {
            $error = new MessageBag([
                'title' => '信息不存在或已删除',
            ]);
            return back()->with(compact('error'));
        }
        $baseForm = new Form($baseInfo);
        $baseForm->disableReset();
        $baseForm->text('rights_title', '权益名称');
        $baseForm->text('rights_desc', '权益描述');
        $baseForm->imgUpload('rights_use_pic', '权益使用说明图片', false, ['isUpload' => true, 'isGetUrl' => true, 'imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE]);
//        $childStatus = self::CHILD_STATUS_OFF;
//        if ($baseInfo['child_ids']) {
//            $childStatus = self::CHILD_STATUS_ON;
//        }
//        $baseForm->select('child_status', '是否组合套餐')
//            ->options(self::CHILD_STATUS_ARR)->when(self::CHILD_STATUS_ON, function (Form $form) {
//
//                $where['rights_type'] = BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM;
//
//                $where['data_status'] = BrandRightsSource::STATUS_NORMAL;
//                $actList = BrandRightsSource::selectList($where, ['id', 'rights_title']);
////                $actIds = [];
////                if ($this->child_status == self::CHILD_STATUS_ON) {
//                $actIds = array_column($actList, 'id');
////                }
//                $actList = array_column($actList, 'rights_title', 'id');
//                // 如果选项太多的话，可以在上面增加一个全选checkbox
//                $form->checkbox('child_ids', "套餐组合")->options($actList)->default($actIds);
//            })->default($childStatus);
        $baseForm->hidden('id');
        $baseForm->confirm('确定更新吗？');
        $baseForm->action('/admin/BrandRights/save');

        return $content
            ->header('修改')
            ->description(' ')
            ->breadcrumb(
                ['text' => '基础权益管理列表', 'url' => '/BrandRights/index'],
                ['text' => '基础权益修改']
            )
            ->row($baseForm);

    }

    /**
     * 保存
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function save(Request $request)
    {
        try {
            $params = $request->all();
            $rules = [
                "rights_title" => 'required',
            ];
            //更新
            $info = BrandRightsSource::getInfo(['id' => $params['id']], ['id']);
            if (!$info) {
                throw new \Exception('该活动不存在！');
            }
            //校验参数
            $res_msg = Common::validatorRule($rules, $params);
            if ($res_msg !== true) {
                throw new \Exception($res_msg);
            }
            $data = [
                "rights_desc" => $params["rights_desc"] ?? '',
                "rights_title" => $params["rights_title"] ?? '',
                "rights_use_pic" => $params["rights_use_pic"] ?? '',

            ];
            $success = new MessageBag([
                'title' => '成功',
            ]);
            //更新
            $this->updateData($params['id'], $data);
//            return redirect('/admin/BrandRights/index/' . $params['id'] . '/edit')->with(compact('success'))->withInput();

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/BrandRights/index')->with(compact('success'));
    }

    /**
     * 更新
     * @param $id
     * @param $data
     * @return void
     */
    private function updateData($id, $data): void
    {
        $where['id'] = $id;
        BrandRightsSource::updateData($data, $where);
    }

    /**
     * 新增
     * @param $data
     * @return void
     */
    private function insertData($data): void
    {
        $data['admin_id'] = Admin::user()->id;
        BrandRightsSource::insertData($data);
    }


    /**
     * 新增
     * @param Content $content
     * @param Form $form
     * @return Content
     */
    public function create(Content $content, Form $form): Content
    {

        $form->disableReset();
        $options = BrandRightsSource::RIGHTS_TYPE_ARR;
        $form->select('rights_type', '权益类型')->options($options)->default(BrandRightsSource::RIGHTS_TYPE_OPEN);
//        $form->text('rights_group ', "权益分类");
        $form->text('rights_title', "权益标题");
        $form->text('rights_name', "权益英文名称");
        $form->textarea('rights_desc ', "权益描述");

//        $form->select('child_status', '是否组合套餐')
//            ->options(self::CHILD_STATUS_ARR)->when(self::CHILD_STATUS_ON, function (Form $form) {
//
//                $where['rights_type'] = BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM;
//
//                $where['data_status'] = BrandRightsSource::STATUS_NORMAL;
//                $actList = BrandRightsSource::selectList($where, ['id', 'rights_title']);
//                $actList = array_column($actList, 'rights_title', 'id');
//                // 如果选项太多的话，可以在上面增加一个全选checkbox
//                $form->checkbox('child_ids', "套餐组合")->options($actList)->canCheckAll();
//            })->default(self::CHILD_STATUS_OFF);

        $form->confirm('确定创建吗？');

        $form->action('/admin/BrandRights/createSave');

        return $content
            ->header('新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '基础权益管理列表', 'url' => '/BrandRights/index'],
                ['text' => '新增']
            )
            ->row($form);
    }


    /**
     * 新增保存
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function createSave(Request $request)
    {
        try {
            $params = $request->all();
            $rules = [
                "rights_title" => 'required',
                "rights_type" => 'required',
                "rights_name" => 'required',
            ];
            //校验参数
            $res_msg = Common::validatorRule($rules, $params);
            if ($res_msg !== true) {
                throw new \Exception($res_msg);
            }
            $rid = BrandRightsSource::getInfo(['rights_name' => $params['rights_name']],"id");
            if ($rid){
                throw new Exception("该权益已存在！");
            }

            $data = [
                "rights_type" => $params["rights_type"] ?? BrandRightsSource::RIGHTS_TYPE_OPEN,
                "rights_name" => $params["rights_name"],
                "rights_desc" => $params["rights_desc"] ?? '',
                "rights_title" => $params["rights_title"] ?? '',
            ];
//            if ($params['child_status'] == self::CHILD_STATUS_ON) {
//                $child_ids = array_filter($params['child_ids']);
//                $data['child_ids'] = implode(",", $child_ids) ?: '';
//            }
            $success = new MessageBag([
                'title' => '成功',
            ]);
            $this->insertData($data);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/BrandRights/index')->with(compact('success'));
    }


}